<?php

namespace app\service;

use OSS\Core\OssException;
use OSS\OssClient;
use think\Db;

class AliOss {
    /**
     * 删除文件
     * @param int $thumb
     * @param int $water
     * @return \think\response\Json
     */
    public static function delete($path = '', $authvalid = true) {
        $switch = getenv('APP_OSS');
        if (!$path || !$switch) {
            return false;
        }
        if ($path == '/disk/uploads/image/20230110/c0ede9e15fb17189fdb95c69380b1b085bbba4dc.png') {
            return false;
        }
        if (strpos($path, 'public/style/api/img') !== false) {
            return false;
        }
        if (strpos($path, '.m3u8') !== false) {
            return self::delFolder($path);
        }
        if ($authvalid) {
            $isauth = Db::name('auth')->where(['image1' => ['like', '%' . $path . '%']])->find();
            if ($isauth) {
                return false;
            }
        }
        $isTempWords = Db::name('privatechat_default')->where(['image' => $path])->find();
        if ($isTempWords) {
            return false;
        }

        if (strpos($path, 'http') === false) {
            $accessKeyId     = getenv('OSS_KEYID');
            $accessKeySecret = getenv('OSS_KEYSECRET');
            $endpoint        = getenv('OSS_ENDPOINT');
            $bucket          = getenv('OSS_BUCKET');
            $thumb = explode('.', $path);
            $thumb[0] .= '_thumb';
            $thumb = implode('.', $thumb);
        } else {
            $accessKeyId     = getenv('RELANG_OSS_KEYID');
            $accessKeySecret = getenv('RELANG_OSS_KEYSECRET');
            $endpoint        = getenv('RELANG_OSS_ENDPOINT');
            $bucket          = getenv('RELANG_OSS_BUCKET');

            $path = '/disk/' . explode('/disk/', $path)[1];
            $thumb = explode('.', $path);
            $thumb[0] .= '_thumb';
            $thumb = implode('.', $thumb);
        }

        if ($path[0] == '/') {
            $path = substr($path, 1);
            $thumb = substr($thumb, 1);
        }

        try {
            $ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint);
            $ossClient->deleteObject($bucket, $path);
            $ossClient->deleteObject($bucket, $thumb);
        } catch (OssException $e) {
            // printf(__FUNCTION__ . ": FAILED\n");
            // printf($e->getMessage() . "\n");
            return false;
        }
        return true;
    }

    /**
     * 删除多个文件
     * @param int $thumb
     * @param int $water
     * @return \think\response\Json
     */
    public static function deletes($paths = []) {
        $switch    = getenv('APP_OSS');
        $path_dels = [];

        $hifiles   = Db::name('privatechat_greet')->where(['content' => ['in', $paths]])->column('content');
        $TempWords = Db::name('privatechat_default')->where(['image' => ['<>', '']])->column('image');
        foreach ($paths as $key => $value) {
            if (in_array($value, $hifiles)) {
                continue;
            }
            if (in_array($value, $TempWords)) {
                continue;
            }
            if (strpos($value, 'public/style/api/img') !== false) {
                continue;
            }
            if (strpos($value, '.m3u8') !== false) {
                self::delFolder($value);
                continue;
            } else if ($value != 'disk/uploads/image/20230110/c0ede9e15fb17189fdb95c69380b1b085bbba4dc.png') {
                $path_dels[] = $value;
            }
        }
        if (sizeof($path_dels) == 0 || !$switch) {
            return false;
        }

        $accessKeyId     = getenv('OSS_KEYID');
        $accessKeySecret = getenv('OSS_KEYSECRET');
        $endpoint        = getenv('OSS_ENDPOINT');
        $bucket          = getenv('OSS_BUCKET');

        try {
            $ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint, false);
            $ossClient->deleteObjects($bucket, $path_dels);
        } catch (OssException $e) {
            // printf(__FUNCTION__ . ": FAILED\n");
            // printf($e->getMessage() . "\n");
            return false;
        }
        return true;
    }

    // 找到以下文件
    // “项目根目录\vendor\aliyuncs\oss-sdk-php\src\OSS\Result\ListObjectsResult.php”
    // 并修改其中如下代码
    // protected function parseDataFromResponse()
    // {
    //      注释这句代码
    //      $xml = new \SimpleXMLElement($this->rawResponse->body);
    //      改为这句代码
    //      $xml = simplexml_load_string($this->rawResponse->body);
    // }
    /**
     * @param $path
     */
    public static function delFolder($path = '') {
        if (strpos($path, 'http') === false) {
            $accessKeyId     = getenv('OSS_KEYID');
            $accessKeySecret = getenv('OSS_KEYSECRET');
            $endpoint        = getenv('OSS_ENDPOINT');
            $bucket          = getenv('OSS_BUCKET');
        } else {
            $accessKeyId     = getenv('RELANG_OSS_KEYID');
            $accessKeySecret = getenv('RELANG_OSS_KEYSECRET');
            $endpoint        = getenv('RELANG_OSS_ENDPOINT');
            $bucket          = getenv('RELANG_OSS_BUCKET');
            $path = '/disk/' . explode('/disk/', $path)[1];
        }
        if ($path[0] == '/') {
            $path = substr($path, 1);
        }
        
        $dirToDelete     = dirname($path) . '/'; // 要删除的文件夹路径

        $ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint);

        // 获取文件夹下的所有文件
        $objects = $ossClient->listObjects($bucket, [
            'prefix'    => $dirToDelete,
            'delimiter' => '/',
        ]);

        // 删除文件夹下的所有文件
        foreach ($objects->getObjectList() as $objectInfo) {
            $ossClient->deleteObject($bucket, $objectInfo->getKey());
        }
        // var_dump($paths);exit;
        // 删除空文件夹
        $res = $ossClient->deleteObject($bucket, rtrim($dirToDelete, '/') . '/');
        // var_dump($res);exit;

        // echo "Folder deleted successfully.";
        return true;
    }
}